package fr.upmc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import fr.upmc.bean.Contact;
import fr.upmc.bean.ContactGroup;
import fr.upmc.bean.PhoneNumber;
import fr.upmc.dao.ContactDAO;
import fr.upmc.utils.HibernateUtils;
import fr.upmc.utils.SessionTracker;

public class SearchContact extends HttpServlet {

	private static final long serialVersionUID = -345334441605968923L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		//if user not connected, get him the hell out of here
		if(!SessionTracker.isUserConnected(request))
		{
			SessionTracker.redirectToHome(response);
		}
		
		Session session = HibernateUtils.getSessionFactory().openSession();
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		long id = -1;
		String name = null;
		try {
			name = request.getParameter("q");
		} catch (Exception e) {
			out.print("error");
			out.close();
			return;
		}

		if(name == null){
			out.print("error");
			out.close();
			return;
		}
		
		try {
			id = Long.parseLong(name);
		} catch (Exception e) {
		}
		
		ContactDAO dao = new ContactDAO(session);
		Contact contact;
		
		//search done by name?
		if(id == -1)
			contact = dao.read(name);
		else
			contact = dao.read(id);

		if(contact != null){
			out.print("<hr/><b>Firstname</b> :" + contact.getFirstName());
			out.println("<br/><b>Lastname</b> :" + contact.getLastName());
			out.println("<br/><b>Email</b> :" + contact.getEmail());
			out.println("<br/><br/><a href='contactDetails.jsp?id="+ contact.getContactId() +"'>Details</a> - <a href='updateContact.jsp?id="+ contact.getContactId() +"'>Update</a> - <a href='deleteContact.jsp?id="+ contact.getContactId() +"'>Delete</a>");
			out.println("<hr/>");
		}
		else{
			out.print("no_result");
		}
		
		out.close();
		session.close();
		
		return;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		doGet(request,response);

		return;
	}
}
